package com.atguigu.tingshu.album.executor;


import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.Map;

@Component
public class AlbumJobExecutor {
    @Autowired
    OrderInfoFeignClient orderInfoFeignClient;
    @Autowired
    AlbumStatMapper albumStatMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    private static Logger logger = LoggerFactory.getLogger(AlbumJobExecutor.class);

    //更新排行榜: 1小时更新一次
    @XxlJob("updateAlbumState") //更新专辑声音统计数据 同时同步到es中！
    @Transactional(rollbackFor = Exception.class)
    public void updateAlbumState(){
        logger.info("更新专辑销量：{}" , new Date());
        XxlJobHelper.log("开始更新专辑销量：{}" , new Date());

        /*
            保存专辑统计数据：
                album_stat表：
             第二天查询前一天支付成功的订单 得到购买的专辑id 统计数量
         */
        //1、查询统计数据
        String date = new DateTime().minusDays(1).toString("yyyy-MM-dd");
        Result<Map<Long , Integer>> mapResult = orderInfoFeignClient.getOrderSaleStates(date);
//        AssertUtil.resultAssert(mapResult, ResultCodeEnum.DATA_ERROR);
        if(mapResult==null || CollectionUtils.isEmpty(mapResult.getData())){
            return;//没有查询到统计数据
        }
        //2、更新统计数据
        Map<Long , Integer> albumStates = mapResult.getData();
        albumStates.forEach( (k,v)->{
            albumStatMapper.updateAlbumStat(k,v , SystemConstant.ALBUM_STAT_BROWSE);
        });
        //发送mq消息：通知搜索模块 同步 专辑的统计数据
        rabbitTemplate.convertAndSend(RabbitConstant.ALBUM_EXCHANGE ,
                RabbitConstant.ALBUM_UPDATE_SALES_RK
                ,albumStates);


        logger.info("更新专辑销量成功：{}" , new Date());
        XxlJobHelper.log("更新专辑销量成功：{}", new Date());

    }
}
